package com.example.cart.service.impl;

import com.example.cart.domain.dto.CartDTO;
import com.example.cart.domain.po.Cart;
import com.example.cart.domain.vo.CartVO;
import com.example.cart.domain.vo.OrderPreGoods;
import com.example.cart.domain.vo.OrderPreVO;
import com.example.cart.mapper.CartMapper;
import com.example.cart.service.CartService;
import com.example.common.context.BaseContext;
import com.example.common.domain.Result;
import com.example.product.api.client.ProductClient;
import com.example.product.domain.vo.ProductVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class CartServiceImpl implements CartService {
    private final ProductClient productClient;
    private final CartMapper cartMapper;

    /**
     * 获取购物车信息
     *
     * @return
     */
    @Override
    public List<CartVO> getCart() {
        Long currentId = BaseContext.getCurrentId();
        // 查询当前用户的购物车数据
        List<Cart> cartList = cartMapper.selectCartByUserId(currentId);
        // 判断购物车数据是否有效
        if (cartList == null || cartList.isEmpty()) {
            return null;
        }
        List<CartVO> cartVOList = new ArrayList<>();
        List<Long> itemIds = new ArrayList<>();
        // 2.转换VO,处理VO中的商品信息
        cartList.forEach(cart -> {
            CartVO cartVO = new CartVO();
            BeanUtils.copyProperties(cart, cartVO);
            itemIds.add(cart.getItemId());
            cartVOList.add(cartVO);
        });
        // 3. 远程调用获取商品信息
        Result<Map<Long, ProductVO>> productInfo = productClient.getProduct(itemIds);
        cartVOList.forEach(cartVO -> {
            ProductVO productVO = productInfo.getData().get(cartVO.getItemId());
            // 设置商品是否有效
            cartVO.setStatus(productVO.getStatus() == 1);
            // 设置商品名称
            cartVO.setName(productVO.getName());
            // 设置现在的商品价格
            cartVO.setNowPrice(productVO.getPrice());
            // 设置商品库存
            cartVO.setStock(productVO.getStock());
            // 设置商品规格
            cartVO.setAttrsText(productVO.getSpecs());
            // 设置商品id
            cartVO.setProductId(productVO.getProductId());
        });

        return cartVOList;
    }

    /**
     * 添加购物车
     *
     * @param cartDTO
     */
    @Override
    public void addCart(CartDTO cartDTO) {
        // 判断当前用户购物车中是否已存在该商品
        Cart cartQuery = new Cart();
        Long currentId = BaseContext.getCurrentId();
        cartQuery.setUserId(currentId);
        cartQuery.setItemId(cartDTO.getItemId());

        // 查询购物车中是否已存在该商品
        Cart existingCart = cartMapper.getCartByUserIdAndItemId(cartQuery);

        if (existingCart != null) {
            // 如果已存在，则更新数量
            existingCart.setNum(existingCart.getNum() + cartDTO.getNum());
            existingCart.setUpdateTime(LocalDateTime.now());
            cartMapper.updateCart(existingCart);
        } else {
            // 如果不存在，则新增商品
            Cart cart = new Cart();
            BeanUtils.copyProperties(cartDTO, cart);
            cart.setUserId(currentId);
            cart.setCreateTime(LocalDateTime.now());
            cart.setUpdateTime(LocalDateTime.now());
            cartMapper.insertCart(cart);
        }
    }


    /**
     * 删除购物车
     *
     * @param ids
     */

    @Override
    public void deleteCart(List<Long> ids) {
        Long currentId = BaseContext.getCurrentId();
        cartMapper.deleteCart(ids, currentId);
    }

    /**
     * 修改购物车
     *
     * @param cartDTO
     */
    @Override
    public void updateCart(CartDTO cartDTO) {
        Long currentId = BaseContext.getCurrentId();
        Cart cart = new Cart();
        BeanUtils.copyProperties(cartDTO, cart);
        cart.setUserId(currentId);
        cart.setUpdateTime(LocalDateTime.now());
        cartMapper.updateCart(cart);

    }

    /**
     * 修改购物车商品选中状态
     *
     * @param selected
     */
    @Override
    public void updateCartSelected(Integer selected) {
        Long currentId = BaseContext.getCurrentId();
        Cart cart = Cart.builder()
                .userId(currentId)
                .selected(selected)
                .updateTime(LocalDateTime.now())
                .build();
        cartMapper.updateCartSelected(cart);
    }

    /**
     * 获取预下单信息
     *
     * @return
     */
    @Override
    public OrderPreVO getPreOrder() {
        Long currentId = BaseContext.getCurrentId();
        List<Cart> preVOList = cartMapper.selectOrderPre(currentId);
        List<Long> itemIds = new ArrayList<>();
        List<OrderPreGoods> orderPreGoodList = new ArrayList<>();
        OrderPreVO orderPreVO = new OrderPreVO();
        preVOList.forEach(cart -> {
            OrderPreGoods orderPreGoods = new OrderPreGoods();
            BeanUtils.copyProperties(cart, orderPreGoods);

            itemIds.add(cart.getItemId());
            orderPreGoodList.add(orderPreGoods);
        });
        Result<Map<Long, ProductVO>> productInfo = productClient.getProduct(itemIds);
        orderPreGoodList.forEach(orderPreGoods -> {
            ProductVO productVO = productInfo.getData().get(orderPreGoods.getItemId());
            orderPreGoods.setProductId(productVO.getProductId());
            orderPreGoods.setName(productVO.getName());
            orderPreGoods.setNowPrice(productVO.getPrice());
            orderPreGoods.setAttrsText(productVO.getSpecs());
            // 计算总价
            BigDecimal totalPrice = new BigDecimal(orderPreGoods.getNum()).multiply(orderPreGoods.getNowPrice());
            // 设置每一种商品的总价
            orderPreGoods.setTotalPrice(totalPrice);
        });
        orderPreVO.setTotalPrice(calculateTotalPrice(orderPreGoodList));
        // 计算邮费
        orderPreVO.setPostFee(calculatePostFee(orderPreVO.getTotalPrice(), preVOList.size()));
        // 计算支付总额
        orderPreVO.setTotalPayPrice(orderPreVO.getTotalPrice().add(orderPreVO.getPostFee()));
        orderPreVO.setOrderPreGoods(orderPreGoodList);
        return orderPreVO;
    }

    private BigDecimal calculateTotalPrice(List<OrderPreGoods> orderPreGoodList) {
        /*BigDecimal totalPrice = orderPreGoodList.stream()
                .map(OrderPreGoods::getTotalPrice)
                .reduce(BigDecimal.ZERO, BigDecimal::add);*/
        BigDecimal totalPrice = new BigDecimal(0);
        for (int i = 0; i < orderPreGoodList.size(); i++) {
            totalPrice = totalPrice.add(orderPreGoodList.get(i).getTotalPrice());
        }
        return totalPrice;
    }


    @Override
    public OrderPreVO getPreOrderNow(Long skuId, Integer count) {
        OrderPreGoods orderPreGoods = new OrderPreGoods();
        OrderPreVO orderPreVO = new OrderPreVO();

        List<Long> itemIds = new ArrayList<>();
        itemIds.add(skuId);
        Result<Map<Long, ProductVO>> productInfo = productClient.getProduct(itemIds);

        ProductVO productVO = productInfo.getData().get(skuId);
        orderPreGoods.setProductId(productVO.getProductId());
        orderPreGoods.setName(productVO.getName());
        orderPreGoods.setNowPrice(productVO.getPrice());
        orderPreGoods.setAttrsText(productVO.getSpecs());
        orderPreGoods.setItemId(skuId);
        orderPreGoods.setNum(count);
        orderPreGoods.setImage(productVO.getSkuImage());
        BigDecimal totalPrice = productVO.getPrice().multiply(new BigDecimal(count));
        orderPreGoods.setTotalPrice(totalPrice);
        orderPreVO.setTotalPrice(totalPrice);
        orderPreVO.setPostFee(calculatePostFee(orderPreVO.getTotalPrice(), count));
        orderPreVO.setTotalPayPrice(orderPreVO.getTotalPrice().add(orderPreVO.getPostFee()));

        List<OrderPreGoods> orderPreGoodList = new ArrayList<>();
        orderPreGoodList.add(orderPreGoods);
        orderPreVO.setOrderPreGoods(orderPreGoodList);

        return orderPreVO;
    }

    /**
     * 计算订单邮费
     *
     * @param totalPrice   商品总价
     * @param productCount 商品总数量
     * @return 邮费金额
     */
    private BigDecimal calculatePostFee(BigDecimal totalPrice, Integer productCount) {
        // 基础邮费策略：满额免邮
        BigDecimal freeShippingThreshold = new BigDecimal("88.00"); // 满88元免邮
        BigDecimal basePostFee = new BigDecimal("8.00"); // 基础邮费8元

        // 如果订单金额达到免邮门槛，则免邮
        if (totalPrice.compareTo(freeShippingThreshold) >= 0) {
            return BigDecimal.ZERO;
        }

        // 按件数计算邮费（可选策略）
        // BigDecimal piecePostFee = new BigDecimal(productCount).multiply(new BigDecimal("2.00"));
        // return piecePostFee.max(basePostFee); // 取按件计算和基础邮费的较大值

        // 简单返回基础邮费
        return basePostFee;
    }

}
